﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using Common;
using Common.Constant;

public partial class Post : System.Web.UI.Page
{
    private Entity.Post _post;
    private PostBus _postBus;
    private CategoryBus _categoryBus;
    protected void Page_Load(object sender, EventArgs e)
    {

        //if(Session["username"] == null)
        //{
        //    Response.Redirect("Default.aspx");
        //}
        if(!IsPostBack)
        {
            LoadCategory();
            if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["ac"] == "edit")
            {
                try
                {
                    int postId = int.Parse(Request.QueryString["id"]);
                    LoadEditData(postId);
                    pnView.Visible = false;
                    pnEditor.Visible = true;
                    btnSubmitPost.Text = "Lưu sửa đổi";
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["ac"] == "Publish")
            {
                try
                {
                    int postId = int.Parse(Request.QueryString["id"]);
                    _postBus = new PostBus();
                    _postBus.PublishPost(postId, true);
                    Response.Redirect("Post.aspx?ac=view");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["ac"] == "UnPublish")
            {
                try
                {
                    int postId = int.Parse(Request.QueryString["id"]);
                    _postBus = new PostBus();
                    _postBus.PublishPost(postId, false);
                    Response.Redirect("Post.aspx?ac=view");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else if(Request.QueryString["ac"] == "add")
            {
                pnView.Visible = false;
                pnEditor.Visible = true;
                ResetAll();
            }
            else
            {
                LoadPostByUserName();
                pnView.Visible = true;
                pnEditor.Visible = false;
            }
        }
        InitEditor();
    }

    protected void InitEditor()
    {
        txtContent.ToolbarStartupExpanded = false;
        txtContent.config.toolbar = new object[]
			{
				new object[] { "Source", "-", "Save", "NewPage", "Preview", "-", "Templates" },
                new object[] { "Bold", "Italic", "Underline", "Strike", "-", "Subscript", "Superscript" },
                new object[] { "NumberedList", "BulletedList", "-", "Outdent", "Indent", "Blockquote", "CreateDiv" },
				"/",
				new object[] { "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock" },
				new object[] { "Link", "Unlink", "Anchor" },
				new object[] { "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe" },
                new object[] { "BidiLtr", "BidiRtl" },
				"/",
				new object[] { "Styles", "Format", "Font", "FontSize" },
				new object[] { "TextColor", "BGColor" },
				new object[] { "Maximize", "ShowBlocks", "-", "About" }
			};
    }

    public void LoadPostByUserName()
    {
        if (Session["User"] != null)
        {
            string username = Session["User"].ToString();
            _postBus = new PostBus();
            DataSet listPost = _postBus.GetPostByUserForManager(username);
            RepeaterListPost.DataSource = listPost;
            RepeaterListPost.DataBind();
        }
    }

    protected void BtnUploadClick(Object sender, EventArgs e)
    {
        UploadPhoto(fuPhoto);
    }

    protected void UploadPhoto(FileUpload fu)
    {
        if (fu.HasFile)
        {
            try
            {
                if (fu.PostedFile.ContentType == "image/jpeg" || fu.PostedFile.ContentType == "image/gif" || fu.PostedFile.ContentType == "image/png")
                {
                    if (fu.PostedFile.ContentLength < 4096000)
                    {
                        const int thumbWidth = 150;
                        const int thumbHeight = 110;

                        System.Drawing.Image oImg = System.Drawing.Image.FromStream(fu.PostedFile.InputStream);
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        System.Drawing.Image phoi = new Bitmap(Server.MapPath("~/resource/images/b.png"));

                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        var oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oGraphic.DrawImage(phoi, 120, 80);

                        string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                        oThumbNail.Save(Server.MapPath("~/resource/upload/") + filename, ImageFormat.Jpeg);
                        oImg.Dispose();

                        txtPhoto.Text = "resource/upload/" + filename;
                        lblMessage.Text = UIMessage.UploadSuccess;
                        lblMessage.ForeColor = Color.Blue;
                    }
                    else
                        lblMessage.Text = UIMessage.MaxUploadSize;
                }
                else
                    lblMessage.Text = UIMessage.OnlyImageFileAccepted;
            }
            catch (Exception ex)
            {
                lblMessage.Text = UIMessage.UploadError + ex.Message;
            }
        }
    }

    protected void LoadEditData(int postId)
    {
        _postBus = new PostBus();
        var data = _postBus.GetPostById(postId);
        if(data.Tables[0].Rows.Count>0)
        {
            txtPostName.Text = data.Tables[0].Rows[0]["PostName"].ToString();
            txtDescription.Text = data.Tables[0].Rows[0]["PostDescription"].ToString();
            txtContent.Text = data.Tables[0].Rows[0]["PostContent"].ToString();
            txtPhoto.Text = data.Tables[0].Rows[0]["PicturePath"].ToString();
            hViewCount.Value = data.Tables[0].Rows[0]["ViewCount"].ToString();
            hCommentCount.Value = data.Tables[0].Rows[0]["CommentCount"].ToString();
            hUserName.Value = data.Tables[0].Rows[0]["UserName"].ToString();
            drdCategory.SelectedValue = data.Tables[0].Rows[0]["CategoryId"].ToString();
            hPostDate.Value = data.Tables[0].Rows[0]["Postdate"].ToString();
            btnSubmitPost.Text = "Lưu sửa đổi";
            btnSubmitPost.CommandName = "edit";
        }
        
    }

    private void LoadCategory()
    {
        _categoryBus = new CategoryBus();
        DataSet allCategory = _categoryBus.SelectAllCategory();
        drdCategory.DataTextField = "CatName";
        drdCategory.DataValueField = "CatId";
        drdCategory.DataSource = allCategory;
        drdCategory.DataBind();
    }

    protected void SubmitPost(object sender,EventArgs e)
    {
        try
        {
            _postBus = new PostBus();
            if(btnSubmitPost.Text == "Lưu sửa đổi")
            {
                _post = new Entity.Post
                            {
                                PostId = int.Parse(Request.QueryString["id"]),
                                CategoryId = int.Parse(drdCategory.SelectedValue),
                                PostName = txtPostName.Text,
                                PostDescription = txtDescription.Text,
                                PostContent = txtContent.Text,
                                Postdate = DateTime.Parse(hPostDate.Value),
                                PicturePath = (txtPhoto.Text == "") ? "resource/upload/post/nopic.jpg" : txtPhoto.Text,
                                UserName = hUserName.Value,
                                ViewCount = int.Parse(hViewCount.Value),
                                CommentCount = int.Parse(hCommentCount.Value)
                };
                UIMessage.ShowMessage(_postBus.UpdatePost(_post) ? "Chỉnh sửa bài viết thành công !" : "Chỉnh sửa bài viết thất bại !", this);
            }
            else
            {
                _post = new Entity.Post
                {
                    CategoryId = int.Parse(drdCategory.SelectedValue),
                    PostName = txtPostName.Text,
                    PostDescription = txtDescription.Text,
                    PostContent = txtContent.Text,
                    Postdate = DateTime.Now,
                    PicturePath = (txtPhoto.Text == "") ? "resource/upload/post/nopic.jpg" : txtPhoto.Text,
                    UserName = Session["User"].ToString(),
                    ViewCount = 0,
                    CommentCount = 0,
                    IsPublish = true
                };
                UIMessage.ShowMessage(_postBus.AddPost(_post) ? "Đăng bài viết thành công !" : "Đăng bài viết thất bại !", this);
            }
            
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

    private void ResetAll()
    {
        txtPostName.Text = "";
        txtContent.Text = "";
        txtDescription.Text = "";
        txtPhoto.Text = "";
    }
}
